import React, { useEffect, FC, useState } from 'react'
import { Menu } from 'antd'
import { useLocation, useNavigate } from 'react-router-dom'
import { Scrollbars } from 'react-custom-scrollbars-2'
import { IRoute, MenuInfo } from '@/typings/router'
import { rootRouter, routerArray } from '@/router'
import { useStore } from '@/store'
import { observer } from 'mobx-react'

const SiderMenu: FC = () => {
  const location = useLocation()
  const navigate = useNavigate()
  const { pathname } = location
  const [openMenu, setOpenMenu] = useState(`/${pathname.split('/')[1]}`)
  const { appStore, tagStore } = useStore()
  const openKey: Array<string> = [pathname]

  useEffect(() => {
    pathname !== '/' && handleDefaultSelect()
  }, [pathname])

  const getMenuTree = (routers: IRoute[]) => {
    return routers.reduce((pre: any, item: any) => {
      if (!item.hidden) {
        pre.push(item)
      }
      return pre
    }, [])
  }

  const menuTree = getMenuTree(rootRouter)

  const selectBreadcrumb = (currentKey: string, path: string) => {
    const currentMenu: any = []

    const findItem = (item: any) => {
      item.children.forEach((sItem: any) => {
        if (path.includes(sItem.path)) {
          currentMenu.push({ label: sItem.label, path: sItem.path })
        }
        if (sItem.children) {
          findItem(sItem)
        }
      })
    }

    routerArray.forEach((item: any) => {
      if (item.path === currentKey) {
        currentMenu.push({ label: item.label, path: item.path })
      }
      if (item.children) {
        findItem(item)
      }
    })

    return currentMenu
  }

  // 刷新页面，处理默认选中
  const handleDefaultSelect = () => {
    const currentKey = `/${pathname.split('/')[1]}`
    const currentMenu = selectBreadcrumb(currentKey, pathname)

    setOpenMenu(currentKey)
    appStore.setCurrentMenuList(currentMenu)
    tagStore.addTag({ label: '公告板', key: '/basic/dashboard' })
  }

  const handleMenuClick = (item: MenuInfo) => {
    const currentKey = `/${item.key.split('/')[1]}`
    const path = item.key
    const currentMenu = selectBreadcrumb(currentKey, path)

    appStore.setCurrentMenuList(currentMenu)
    setOpenMenu(currentKey)
    navigate(item.key)
    tagStore.addTag({ label: item.item.props.title, key: item.key })
  }

  return (
    <div className="app-sider-menu">
      <Scrollbars style={{ height: (window.innerHeight - 64) }}>
        <Menu mode="inline" theme="dark" inlineIndent={15} items={menuTree} selectedKeys={openKey} defaultOpenKeys={[openMenu]} onClick={handleMenuClick} className="app-menu-inner" />
      </Scrollbars>
    </div>
  )
}

export default observer(SiderMenu)
